package org.framework.gofun.mongodb.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.framework.gofun.mongodb.service.MongoService;
import org.framework.gofun.mongodb.utils.MongoCollectionsUtil;
import org.framework.gofun.mongodb.utils.PageUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;

@Service("mongoService")
public class MongoServiceImpl  implements MongoService{

	@Resource
	private MongoTemplate mongoTemplate;
	
	/**
	 * count查询
	 * @param query
	 * @param entityClass
	 * @return
	 */
	@Override
	public long count(Query query, Class<?> entityClass){
		return mongoTemplate.count(query, MongoCollectionsUtil.getCollectionName(entityClass));
	}
	
	
	@Override
	public <T> List<T> find(Query query, Class<T> entityClass){
		return mongoTemplate.find(query, entityClass , MongoCollectionsUtil.getCollectionName(entityClass));
	}
	
	@Override
	public <T>  PageInfo<T> findPage(Query query,Integer pageNum,Integer pageSize,Class<T> entityClass){
		long count = count(query, entityClass);
		Page<T> page = new Page<T>(pageNum, pageSize, Boolean.FALSE);
		page.setTotal(count);
		query.skip(page.getStartRow());// skip相当于从那条记录开始
        query.limit(page.getPageSize());// 从skip开始,取多少条记录  
        List<T> list = mongoTemplate.find(query, entityClass , MongoCollectionsUtil.getCollectionName(entityClass));
        page.addAll(list);
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        page.setTotal(count);
       return  PageUtil.toPageInfo(page);
	
	}
	
	/**
	 *插入
	 * @param object
	 */
	public void insert(Object object){
		mongoTemplate.insert(object , MongoCollectionsUtil.getCollectionName(object.getClass()));;
	}
	
	/**
	 * 删除
	 * @param object
	 */
	public void remove(Object object){
		mongoTemplate.remove(object , MongoCollectionsUtil.getCollectionName(object.getClass()));
	}
}
